<template>
  <div class="checkout">
    <NavBar>
      <template #default> 订单确认 </template>
    </NavBar>

    <!-- 收货信息部分 -->
    <div class="shipping-section">
      <div class="section-title">收货信息</div>
      <el-form :model="shippingInfo" :rules="shippingRules" ref="shippingForm">
        <el-form-item prop="name" label="收货人">
          <el-input
            v-model="shippingInfo.name"
            placeholder="请输入收货人姓名"
          />
        </el-form-item>
        <el-form-item prop="phone" label="联系电话">
          <el-input v-model="shippingInfo.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item prop="address" label="收货地址">
          <el-input
            type="textarea"
            v-model="shippingInfo.address"
            placeholder="请输入详细收货地址"
            :rows="2"
          />
        </el-form-item>
        <el-form-item label="物流公司" class="shipping-company">
          <el-tag>{{ shippingCompanyName }}</el-tag>
        </el-form-item>
      </el-form>
      <el-form-item label="订单备注">
        <el-input
          v-model="remark"
          type="textarea"
          rows="2"
          placeholder="选填，请填写其他需求"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
    </div>

    <!-- 商品信息 -->
    <div class="order-section">
      <div class="section-title">商品信息</div>
      <div class="product-list">
        <div v-for="item in products" :key="item.id" class="product-item">
          <img :src="item.image_url" :alt="item.name" />
          <div class="product-info">
            <div class="name">{{ item.name }}</div>
            <div class="price-count">
              <span class="price">¥{{ item.price }}</span>
              <span class="count">x{{ item.count }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 订单金额 -->
    <div class="amount-section">
      <div class="section-title">订单金额</div>
      <div class="amount-list">
        <div class="amount-item">
          <span>商品总价</span>
          <span class="price">¥{{ totalPrice }}</span>
        </div>
        <div class="amount-item">
          <span>运费</span>
          <span class="price">¥{{ shippingFee }}</span>
        </div>
      </div>
      <div class="total-amount">
        <span>实付金额</span>
        <span class="price">¥{{ totalAmount }}</span>
      </div>
    </div>

    <!-- 底部提交栏 -->
    <div class="submit-bar">
      <div class="amount-info">
        实付金额：<span class="price">¥{{ totalAmount }}</span>
      </div>

      <el-button
        type="danger"
        :loading="submitting"
        :disabled="
          !shippingInfo.name || !shippingInfo.phone || !shippingInfo.address
        "
        @click="handleSubmit"
      >
        提交订单
      </el-button>
    </div>
  </div>
</template>

<script setup>
import NavBar from "@/components/common/NavBar.vue";
import { ref, computed, onMounted, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useCartStore } from "@/stores/modules/cart";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowRight } from "@element-plus/icons-vue";

import { createOrder, createPayment } from "@/apis/OrderApi";
import { getProductDetail } from "@/apis/GoodApi";
import { useUserStore } from "@/stores/modules/user";

const route = useRoute(); // 用于获取路由参数
const router = useRouter(); // 用于路由跳转
const cartStore = useCartStore(); // 用于获取购物车数据
const userStore = useUserStore(); // 用于获取用户信息

// 快递公司列表
const SHIPPING_COMPANIES = {
  SF: "顺丰快递",
  YTO: "圆通快递",
  ZTO: "中通快递",
  YD: "韵达快递",
};

// 响应式数据:  收货信息
const shippingInfo = reactive({
  name: "张三",
  phone: "15386490869",
  address: "湖南工学院",
  // 随机选择一个快递公司代码
  company:
    Object.keys(SHIPPING_COMPANIES)[
      Math.floor(Math.random() * Object.keys(SHIPPING_COMPANIES).length)
    ],
});
// 添加一个计算属性用于显示快递公司名称
const shippingCompanyName = computed(() => {
  return SHIPPING_COMPANIES[shippingInfo.company] || "未知快递";
});

// 收货信息验证规则
const shippingRules = {
  name: [
    { required: true, message: "请输入收货人姓名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  address: [
    { required: true, message: "请输入收货地址", trigger: "blur" },
    { min: 5, max: 100, message: "长度在 5 到 100 个字符", trigger: "blur" },
  ],
};

const shippingForm = ref(null); // 用于获取表单实例

// 响应式状态
const selectedAddress = ref(null); // 选中的收货地址
const products = ref([]); // 订单商品列表
const remark = ref("快快快"); // 订单备注
const submitting = ref(false); // 是否正在提交订单
const shippingFee = ref(0); // 运费

// 计算总价
const totalPrice = computed(() => {
  return products.value.reduce((sum, item) => sum + item.price * item.count, 0);
});

// 计算实付金额
const totalAmount = computed(() => {
  return totalPrice.value + shippingFee.value;
});

// 初始化订单商品
const initOrderProducts = async () => {
  if (route.query.source === "cart") {
    // 从购物车来
    products.value = cartStore.cartList.filter((item) => item.selected);
  } else if (route.query.source === "direct") {
    // 直接购买，获取商品信息
    try {
      // 使用封装的请求方法
      const res = await getProductDetail(route.query.productId);

      // console.log(res.data);
      // 将来上线后，需要修改为下面的代码
      if (res?.data?.code === 200 && res.data.data) {
        products.value = [
          {
            ...res.data.data,
            count: Number(route.query.quantity) || 1,
          },
        ];
      } else {
        throw new Error(res?.data?.message || "获取商品信息失败");
      }
    } catch (error) {
      console.error("获取商品信息失败:", error);
      ElMessage.error("获取商品信息失败");
      router.back();
    }
  } else {
    ElMessage.error("无效的订单来源");
    router.back();
  }
};

// 提交订单
const handleSubmit = async () => {
  if (!shippingForm.value) return;

  await shippingForm.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning("请完善收货信息");
      return;
    }
    try {
      submitting.value = true;
      // 创建订单
      const orderData = {
        userId: userStore.userInfo.id, // 从用户状态获取
        shippingName: shippingInfo.name,
        shippingPhone: shippingInfo.phone,
        shippingAddress: shippingInfo.address,
        shippingCompany: shippingInfo.company,
        cartItems: products.value.map((item) => ({
          productId: item.id,
          quantity: item.count,
        })),
      };

      const orderRes = await createOrder(orderData);
      if (orderRes.data.code !== 200) {
        throw new Error(orderRes.data.message || "创建订单失败");
      }

      // 创建支付
      const paymentData = {
        outTradeNo: orderRes.data.data.orderNo,
        totalAmount: totalAmount.value.toString(),
        subject: `商城订单-${orderRes.data.data.orderNo}`,
      };

      const paymentRes = await createPayment(paymentData);
      if (paymentRes.data.code !== 200) {
        throw new Error(paymentRes.data.message || "创建支付失败");
      }

      // 提交支付表单
      const div = document.createElement("div");
      div.innerHTML = paymentRes.data.data.formHtml;
      document.body.appendChild(div);

      const form = div.getElementsByTagName("form")[0];
      if (!form) {
        throw new Error("支付表单生成失败");
      }
      form.setAttribute("target", "_blank");
      form.submit();

      // 清理DOM
      document.body.removeChild(div);

      // 清理购物车
      if (route.query.source === "cart") {
        products.value.forEach((item) => cartStore.removeFromCart(item.id));
      }

      // 显示支付提示
      ElMessageBox.alert("已在新窗口打开支付页面，请完成支付", "订单提交成功", {
        confirmButtonText: "确定",
        callback: () => {
          router.push("/shopcart");
        },
      });
    } catch (error) {
      console.error("提交订单失败:", error);
      ElMessage.error(error.message || "提交订单失败");
    } finally {
      submitting.value = false;
    }
  });
};

onMounted(() => {
  initOrderProducts();
});
</script>


  <style scoped>
.checkout {
  padding-bottom: 70px; /* 增加底部间距，避免被提交栏遮挡 */
}

.submit-bar {
  z-index: 1000; /* 确保提交栏始终显示在最上层 */
}

.shipping-section {
  background: #fff;
  margin-bottom: 10px;
  padding: 30px 15px 15px;
}

.shipping-company {
  margin-bottom: 0;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}

:deep(.el-input__inner) {
  background: #f8f8f8;
  border: none;
}

.checkout {
  min-height: 100vh;
  min-width: 100vw;
  background: #f5f5f5;
  padding-bottom: 60px;
}

.section-title {
  font-size: 14px;
  color: #666;
  padding: 15px;
  margin: 0;
}

.address-section {
  margin-bottom: 10px;
  background: #fff;
}

.address-content {
  padding: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.address-info {
  flex: 1;
}

.user-info {
  margin-bottom: 8px;
}

.name {
  font-size: 16px;
  margin-right: 10px;
}

.phone {
  color: #666;
}

.address {
  color: #333;
  font-size: 14px;
}

.no-address {
  color: #999;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.order-section {
  margin-bottom: 10px;
  background: #fff;
}

.product-list {
  padding: 0 15px;
}

.product-item {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #f5f5f5;
}

.product-item:last-child {
  border-bottom: none;
}

.product-item img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 10px;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.name {
  font-size: 14px;
  color: #333;
}

.price-count {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.count {
  color: #999;
}

.amount-section {
  margin-bottom: 10px;
  background: #fff;
}

.amount-list {
  padding: 0 15px;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  font-size: 14px;
  color: #666;
}

.total-amount {
  display: flex;
  justify-content: space-between;
  padding: 15px;
  border-top: 1px solid #f5f5f5;
  font-size: 14px;
  font-weight: bold;
}

.remark-section {
  background: #fff;
  padding: 0 15px 15px;
}

.submit-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.amount-info {
  font-size: 14px;
}

.amount-info .price {
  font-size: 18px;
}

:deep(.el-textarea__inner) {
  background: #f8f8f8;
  border: none;
}
</style>
